package com.youzhi.backend.controller;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youzhi.backend.dto.Result;
import com.youzhi.backend.exception.EcpEnum;
import com.youzhi.backend.exception.YouZhiException;
import com.youzhi.backend.request.PageRequest;
import com.youzhi.backend.service.ICommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/common")
@Api(tags = "通用查询")
public class CommonController extends BaseController {


    @Autowired
    private ICommonService commonService;


    @PostMapping("/check/repeat/{tableName}/")
    @ApiOperation("字段重复检查")
    public Result checkRepeat(@PathVariable("tableName") String tableName, @RequestBody Map<String, Object> params) {
        if (CollUtil.isEmpty(params)) {
            throw YouZhiException.newException(EcpEnum.query_params_is_empty);
        }
        Long count = commonService.count(tableName, params);
        return Result.ok("count", count);
    }


    /**
     * 通用单表分页查询
     * <p>
     * 简单的分页查询,条件like，排序createTime倒序
     * sort_field=createTime&sort_type=desc
     * @param tableName
     * @param params
     * @return
     */
    @RequiresUser
    @ApiOperation("分页查询")
    @PostMapping("/page/{tableName}/")
    public Result page(@PathVariable("tableName") String tableName, @RequestBody Map<String, Object> params) {
        if (params.get(PageRequest.Fields.size) == null) {
            throw YouZhiException.newException(EcpEnum.field_no_blank, "size");
        }
        if (params.get(PageRequest.Fields.current) == null) {
            throw YouZhiException.newException(EcpEnum.field_no_blank, "current");
        }
        IPage<Map<String, Object>> page = commonService.page(tableName, params);
        return Result.ok(page);
    }


}
